﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AAA.Base.Util.Reader;
using System.Reflection;
using System.IO;

namespace AAA.Command.WCF
{
	public class CommandManager
	{
		private Dictionary<string, string> _dicCommands = new Dictionary<string,string>();
		private IniReader _iniConfig;

		public void AddFolder(string strFolderName)
		{
			DirectoryInfo directoryInfo = new DirectoryInfo(strFolderName);
			FileInfo[] fileInfos = directoryInfo.GetFiles("*.dll");

			foreach(FileInfo fileInfo in fileInfos)
				Add(Assembly.LoadFrom(fileInfo.FullName));
		}

		public void Add(string strDllFileName)
		{
			Add(Assembly.LoadFrom(strDllFileName));
		}

		public void Add(Assembly asmFile)
		{
			string dllFile = asmFile.CodeBase;
			string[] files = asmFile.GetManifestResourceNames();
			string strCommandFile = null;
			foreach(string filename in files)
			{
				if (filename.Contains("command.ini"))
				{ 
					strCommandFile = filename;
					break;
				}
			}
			if(strCommandFile == null) return;

			IniReader iniReader = new IniReader(asmFile.GetManifestResourceStream(strCommandFile));
			foreach (string strCommandName in iniReader.GetKey("Default"))
				Add(strCommandName, dllFile + "," +iniReader.GetParam(strCommandName));
		}

		public void Add(IniReader iniReader)
		{
			foreach (string strCommandName in iniReader.GetKey("Default"))
				Add(strCommandName, iniReader.GetParam(strCommandName));
		}

		public void Add(string strCommandName, string strCommandParameter)
		{
			Add(strCommandName, strCommandParameter, true);
		}

		public void Add(string strCommandName, string strCommandParameter, bool isOverWrite)
		{
			if (!_dicCommands.ContainsKey(strCommandName))
				_dicCommands.Add(strCommandName, strCommandParameter);
			else if (isOverWrite)
				_dicCommands[strCommandName] = strCommandParameter;
		}
		public void Init(string strConfigName)
		{
			_iniConfig = new IniReader(strConfigName);
		}

		public void Init(string strDllFilename, string strFilename)
		{
			_iniConfig = new IniReader(strDllFilename, strFilename);
		}

		public string[] GetCommand(string strCommandName)
		{
			return _dicCommands.ContainsKey(strCommandName)
				? _dicCommands[strCommandName].Split(',')
				: new string[0];
		}
	}
}